#!python3.9
# -*- coding: utf-8 -*-
# @Time    : 2025/2/17 13:15
# @Author  : fy
# @File    : subcmd_driver.py
# @Software: PyCharm
import datetime
import logging
import subprocess
from threading import Timer
from collections import OrderedDict

class SubcmdDriver(object):
    def __init__(self, url):
        self._url = url

    def initialize(self, url):
        pass

    def query(self, stmt, timeout=0, return_tuples=False):
        """
        use OrderedDict to return data
        """
        code, cxt = self.subcommand(stmt, timeout)
        if return_tuples:
            data = []
            try:
                d_dict = eval(cxt.strip("\n"))
                info = d_dict.get('version', '')
                data =[('timetz', datetime.datetime.now(), ('info', info), ('status', code))]
                return data
            except Exception as e:
                return data
        else:
            data = []
            od = OrderedDict()
            if code == 0:
                try:
                    d_dict = eval(cxt.strip("\n"))
                    od['timetz'] = datetime.datetime.now()
                    od['info'] = d_dict.get('version', '')
                    od['status'] = code
                    data.append(od)
                    return data
                except Exception as e:
                    logging.error(e)
                return data
            else:
                return data

    def subcommand(self, cmd, timeout=10):
        child = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        timer = Timer(timeout, lambda process: process.kill(), [child])
        try:
            timer.start()
            stdout, stderr = child.communicate()
            return_code = child.returncode
            if 0 != return_code:
                logging.error("cmd:%s.error code is %d, output is %s", cmd, return_code, stdout.decode('utf-8'))
                return return_code, stdout.decode('utf-8')
            else:
                return return_code, stdout.decode('utf-8')
        finally:
            timer.cancel()